<template>
  <div class="payment-dashboard">
    <!-- 筛选区域 -->
    <el-form :model="filterForm" inline class="filter-bar" label-width="100px">
      <!-- 日期范围 -->
      <el-form-item label="日期">
        <el-date-picker
          v-model="filterForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          :default-value="[new Date('2025-06-01'), new Date('2025-06-20')]"
        />
      </el-form-item>

      <!-- 供应商类别（树弹窗） -->
      <el-form-item label="供应商类别">
        <el-input
          v-model="filterForm.category"
          placeholder="请选择类别"
          readonly
          @click="categoryDialogVisible = true"
        />
      </el-form-item>

      <!-- 供应商（列表弹窗） -->
      <el-form-item label="供应商">
        <el-input
          v-model="filterForm.supplier"
          placeholder="请选择供应商"
          readonly
          @click="supplierDialogVisible = true"
        />
      </el-form-item>

      <!-- 业务员（列表弹窗） -->
      <el-form-item label="业务员">
        <el-input
          v-model="filterForm.salesman"
          placeholder="请选择业务员"
          readonly
          @click="salesmanDialogVisible = true"
        />
      </el-form-item>

      <!-- 查询 & 操作 -->
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="handleExport">导出</el-button>
        <el-button type="info" @click="handlePrint">打印</el-button>
      </el-form-item>
    </el-form>

    <!-- 付款明细表（带合计行） -->
    <el-table
      :data="tableData"
      border
      show-summary
      :summary-method="calcSummary"
      :header-cell-style="{ background: '#F8F9FA' }"
    >
      <el-table-column prop="category" label="供应商类别" width="150" />
      <el-table-column prop="supplierName" label="供应商" width="220" />
      <el-table-column prop="salesmanName" label="业务员" width="120" />
      <el-table-column prop="bizType" label="业务类别" width="120" />
      <el-table-column prop="docDate" label="单据日期" width="120" />
      <el-table-column prop="docNo" label="单据编号" width="160" />
      <el-table-column
        prop="purchaseAmt"
        label="采购金额"
        width="120"
        align="right"
      >
        <template #default="scope">
          <span :style="{ color: scope.row.purchaseAmt < 0 ? 'red' : '#333' }">
            {{ scope.row.purchaseAmt.toFixed(2) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="discountAmt"
        label="优惠金额"
        width="120"
        align="right"
      />
      <el-table-column
        prop="discountedAmt"
        label="优惠后金额"
        width="120"
        align="right"
      />
      <el-table-column
        prop="currentPay"
        label="本次付款"
        width="120"
        align="right"
      />
      <el-table-column
        prop="payableBalance"
        label="应付款余额"
        width="120"
        align="right"
      >
        <template #default="scope">
          <span
            :style="{ color: scope.row.payableBalance < 0 ? 'red' : '#333' }"
          >
            {{ scope.row.payableBalance.toFixed(2) }}
          </span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 供应商类别选择弹窗（树结构） -->
    <el-dialog
      title="选择供应商类别"
      v-model="categoryDialogVisible"
      width="320px"
    >
      <el-tree
        ref="categoryTree"
        :data="categoryTree"
        :props="treeProps"
        show-checkbox
        default-expand-all
        @check="handleCategoryCheck"
      />
      <template #footer>
        <el-button @click="categoryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCategory">确定</el-button>
      </template>
    </el-dialog>

    <!-- 供应商选择弹窗（列表） -->
    <el-dialog title="选择供应商" v-model="supplierDialogVisible" width="640px">
      <el-form :model="supplierSearch" inline class="mb-4">
        <el-form-item label="搜索">
          <el-input
            v-model="supplierSearch.keyword"
            placeholder="编号/名称/联系人"
            clearable
            @keyup.enter="searchSuppliers"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="supplierSearch.showForbidden"
            >显示禁用供应商</el-checkbox
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchSuppliers">查询</el-button>
          <el-button @click="resetSupplierSearch">刷新</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :data="supplierList"
        border
        @selection-change="handleSupplierSelection"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="code" label="编号" width="120" />
        <el-table-column prop="name" label="名称" width="220" />
        <el-table-column prop="type" label="类别" width="120" />
        <el-table-column
          prop="initialPay"
          label="期初应付款"
          width="150"
          align="right"
        />
      </el-table>

      <div class="dialog-footer mt-4">
        <el-pagination
          @size-change="handleSupplierSizeChange"
          @current-change="handleSupplierCurrentChange"
          :current-page="supplierPage.current"
          :page-sizes="[10, 20, 50]"
          :page-size="supplierPage.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="supplierTotal"
          style="float: left"
        ></el-pagination>
        <el-button @click="supplierDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSupplier">确定</el-button>
      </div>
    </el-dialog>

    <!-- 业务员选择弹窗（列表） -->
    <el-dialog title="选择业务员" v-model="salesmanDialogVisible" width="640px">
      <el-form :model="salesmanSearch" inline class="mb-4">
        <el-form-item label="搜索">
          <el-input
            v-model="salesmanSearch.keyword"
            placeholder="职员编号/名称"
            clearable
            @keyup.enter="searchSalesmen"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="salesmanSearch.showForbidden"
            >显示禁用职员</el-checkbox
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchSalesmen">查询</el-button>
          <el-button @click="resetSalesmanSearch">刷新</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :data="salesmanList"
        border
        @selection-change="handleSalesmanSelection"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="code" label="职员编号" width="120" />
        <el-table-column prop="name" label="职员名称" width="220" />
      </el-table>

      <div class="dialog-footer mt-4">
        <el-pagination
          @size-change="handleSalesmanSizeChange"
          @current-change="handleSalesmanCurrentChange"
          :current-page="salesmanPage.current"
          :page-sizes="[10, 20, 50]"
          :page-size="salesmanPage.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="salesmanTotal"
          style="float: left"
        ></el-pagination>
        <el-button @click="salesmanDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSalesman">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "PurchasePaymentDashboard",
  data() {
    return {
      // 筛选条件
      filterForm: {
        dateRange: ["2025-06-01", "2025-06-20"],
        category: "",
        supplier: "",
        salesman: "",
      },

      // 付款数据（模拟5条+小计）
      tableData: [
        {
          category: "酒水饮料供应商",
          supplierName: "G00002 金小蝶食品贸易...",
          salesmanName: "",
          bizType: "普通采购",
          docDate: "2025-06-20",
          docNo: "CG20250620001",
          purchaseAmt: 955.0,
          discountAmt: 0,
          discountedAmt: 955.0,
          currentPay: 0,
          payableBalance: 955.0,
        },
        {
          category: "酒水饮料供应商",
          supplierName: "G00002 金小蝶食品贸易...",
          salesmanName: "",
          bizType: "小计",
          docDate: "",
          docNo: "",
          purchaseAmt: 955.0,
          discountAmt: 0,
          discountedAmt: 955.0,
          currentPay: 0,
          payableBalance: 955.0,
        },
        {
          category: "酒水饮料供应商",
          supplierName: "G00002 金小蝶食品贸易...",
          salesmanName: "",
          bizType: "采购退回",
          docDate: "2025-06-20",
          docNo: "GHT20250620002",
          purchaseAmt: -955.0,
          discountAmt: 0,
          discountedAmt: -955.0,
          currentPay: 0,
          payableBalance: -955.0,
        },
        {
          category: "酒水饮料供应商",
          supplierName: "G00002 金小蝶食品贸易...",
          salesmanName: "",
          bizType: "小计",
          docDate: "",
          docNo: "",
          purchaseAmt: -955.0,
          discountAmt: 0,
          discountedAmt: -955.0,
          currentPay: 0,
          payableBalance: -955.0,
        },
        {
          category: "食品供应商",
          supplierName: "G00003 食品贸易公司",
          salesmanName: "采购-小陈",
          bizType: "普通采购",
          docDate: "2025-06-15",
          docNo: "CG20250615003",
          purchaseAmt: 1500.0,
          discountAmt: 50.0,
          discountedAmt: 1450.0,
          currentPay: 1000.0,
          payableBalance: 450.0,
        },
      ],

      // 供应商类别树
      categoryDialogVisible: false,
      categoryTree: [
        {
          label: "广东",
          children: [
            { label: "海鲜供应商", children: [{ label: "测试" }] },
            { label: "酒水饮料供应商" },
            { label: "食品供应商" },
          ],
        },
        {
          label: "湖南",
          children: [{ label: "辣条供应商" }, { label: "零食供应商" }],
        },
      ],
      treeProps: { children: "children", label: "label" },
      selectedCategory: "",

      // 供应商弹窗
      supplierDialogVisible: false,
      supplierSearch: { keyword: "", showForbidden: false },
      supplierList: [
        { code: "zhongtong", name: "中通快递", type: "物流", initialPay: 0 },
        { code: "yunda", name: "韵达快递", type: "物流", initialPay: 0 },
        { code: "yuantong", name: "圆通速递", type: "物流", initialPay: 0 },
        { code: "sxjdfreight", name: "顺心", type: "物流", initialPay: 0 },
        { code: "ems", name: "EMS", type: "物流", initialPay: 0 },
        { code: "T001", name: "临时供应商", type: "临时", initialPay: 0 },
        { code: "G00009", name: "测试111", type: "测试", initialPay: 0 },
        { code: "G00008", name: "测试", type: "测试", initialPay: 0 },
        { code: "G00007", name: "测试供应商", type: "测试", initialPay: 0 },
        {
          code: "G00003",
          name: "食品贸易公司",
          type: "食品",
          initialPay: 1500,
        },
        {
          code: "G00002",
          name: "金小蝶食品贸易...",
          type: "酒水",
          initialPay: 955,
        },
      ],
      supplierPage: { current: 1, size: 10 },
      supplierTotal: 11,
      selectedSuppliers: [],

      // 业务员弹窗
      salesmanDialogVisible: false,
      salesmanSearch: { keyword: "", showForbidden: false },
      salesmanList: [
        { code: "D0001", name: "老板" },
        { code: "D0002", name: "财务-玲" },
        { code: "D0003", name: "采购-小陈" },
        { code: "D0004", name: "采购-小王" },
        { code: "D0005", name: "销售-小李" },
        { code: "D0006", name: "销售-小东" },
        { code: "D0007", name: "旗舰店店员" },
        { code: "D0008", name: "2店店员" },
        { code: "D0009", name: "1号仓库管员" },
      ],
      salesmanPage: { current: 1, size: 10 },
      salesmanTotal: 9,
      selectedSalesmen: [],
    };
  },
  methods: {
    // 查询逻辑：多条件筛选
    handleQuery() {
      const filtered = this.tableData.filter((item) => {
        const inDate =
          item.docDate >= this.filterForm.dateRange[0] &&
          item.docDate <= this.filterForm.dateRange[1];
        const catMatch =
          !this.filterForm.category ||
          item.category.includes(this.filterForm.category);
        const supMatch =
          !this.filterForm.supplier ||
          item.supplierName.includes(this.filterForm.supplier);
        const salMatch =
          !this.filterForm.salesman ||
          item.salesmanName.includes(this.filterForm.salesman);
        return inDate && catMatch && supMatch && salMatch;
      });
      this.$message.success(`共找到 ${filtered.length} 条数据`);
      console.log("筛选结果：", filtered);
    },

    // 导出功能（示例）
    handleExport() {
      this.$message.info("导出功能待实现");
    },

    // 打印功能（示例）
    handlePrint() {
      this.$message.info("打印功能待实现");
    },

    // 供应商类别树选择
    handleCategoryCheck() {
      const checked = this.$refs.categoryTree.getCheckedNodes();
      this.selectedCategory = checked.length ? checked[0].label : "";
    },
    confirmCategory() {
      this.filterForm.category = this.selectedCategory;
      this.categoryDialogVisible = false;
    },

    // 供应商弹窗：搜索 & 分页
    searchSuppliers() {
      const filtered = this.supplierList.filter((item) => {
        const match =
          !this.supplierSearch.keyword ||
          item.code.includes(this.supplierSearch.keyword) ||
          item.name.includes(this.supplierSearch.keyword);
        return match && (this.supplierSearch.showForbidden || true);
      });
      this.supplierList = filtered;
      this.supplierTotal = filtered.length;
    },
    resetSupplierSearch() {
      this.supplierSearch = { keyword: "", showForbidden: false };
      this.supplierList = [
        /* 原始全量数据 */
      ];
      this.supplierTotal = 11;
    },
    handleSupplierSelection(val) {
      this.selectedSuppliers = val;
    },
    confirmSupplier() {
      this.filterForm.supplier = this.selectedSuppliers
        .map((item) => item.name)
        .join("、");
      this.supplierDialogVisible = false;
    },
    handleSupplierSizeChange(val) {
      this.supplierPage.size = val;
    },
    handleSupplierCurrentChange(val) {
      this.supplierPage.current = val;
    },

    // 业务员弹窗：搜索 & 分页
    searchSalesmen() {
      const filtered = this.salesmanList.filter((item) => {
        const match =
          !this.salesmanSearch.keyword ||
          item.code.includes(this.salesmanSearch.keyword) ||
          item.name.includes(this.salesmanSearch.keyword);
        return match && (this.salesmanSearch.showForbidden || true);
      });
      this.salesmanList = filtered;
      this.salesmanTotal = filtered.length;
    },
    resetSalesmanSearch() {
      this.salesmanSearch = { keyword: "", showForbidden: false };
      this.salesmanList = [
        /* 原始全量数据 */
      ];
      this.salesmanTotal = 9;
    },
    handleSalesmanSelection(val) {
      this.selectedSalesmen = val;
    },
    confirmSalesman() {
      this.filterForm.salesman = this.selectedSalesmen
        .map((item) => item.name)
        .join("、");
      this.salesmanDialogVisible = false;
    },
    handleSalesmanSizeChange(val) {
      this.salesmanPage.size = val;
    },
    handleSalesmanCurrentChange(val) {
      this.salesmanPage.current = val;
    },

    // 表格合计计算（多字段求和）
    calcSummary({ columns, data }) {
      const sums = [];
      columns.forEach((col, i) => {
        if (i === 0) {
          sums[i] = "总计:";
          return;
        }
        const prop = col.prop;
        if (
          [
            "purchaseAmt",
            "discountAmt",
            "discountedAmt",
            "currentPay",
            "payableBalance",
          ].includes(prop)
        ) {
          sums[i] = data
            .reduce((acc, cur) => acc + (cur[prop] || 0), 0)
            .toFixed(2);
        } else {
          sums[i] = "";
        }
      });
      return sums;
    },
  },
};
</script>

<style scoped>
.payment-dashboard {
  padding: 24px;
  background: #fff;
}

.filter-bar {
  margin-bottom: 16px;
}

.el-table {
  margin-top: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 弹窗表格滚动条优化 */
.el-table__body-wrapper {
  max-height: 300px;
  overflow-y: auto;
}
</style>